Skip to content

fix: prevent Vercel Blob upload conflicts on retry#1606

Merged
sweetmantech merged 2 commits intotestfrom
fix/REC-35-file-upload-blob-conflict
Mar 30, 2026
Merged

fix: prevent Vercel Blob upload conflicts on retry#1606
sweetmantech merged 2 commits intotestfrom
fix/REC-35-file-upload-blob-conflict

Conversation

@recoup-coding-agent
Copy link
Copy Markdown
Collaborator

@recoup-coding-agent recoup-coding-agent commented Mar 28, 2026

Summary

  • Add addRandomSuffix: true and allowOverwrite: true to blob upload token generation, preventing "blob already exists" errors on upload retries
  • Use Promise.allSettled for multi-file blob uploads so individual failures don't break the entire batch
  • Surface meaningful error messages when blob uploads fail

Test plan

  • Upload an image via drag-and-drop to sandbox file tree — should succeed
  • Upload same image again — should succeed (no "already exists" error)
  • Upload multiple files where some fail — partial success should be reported

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Enhanced upload resilience: individual file upload failures no longer block the entire upload process; successfully uploaded files proceed even if some fail
    • Automatic filename handling during uploads with random suffix generation and overwrite capability enabled

- Add addRandomSuffix and allowOverwrite to blob upload token options,
  preventing "blob already exists" errors on retry uploads
- Use Promise.allSettled for resilient multi-file blob uploads
- Surface meaningful error messages when blob uploads fail

Co-Authored-By: Paperclip <noreply@paperclip.ing>
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Mar 28, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-chat Ready Ready Preview Mar 30, 2026 2:40am

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 28, 2026

Warning

Rate limit exceeded

@sweetmantech has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 57 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 7 minutes and 57 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ad9829a3-77c4-43a3-92f0-fe53f87b4ce4

📥 Commits

Reviewing files that changed from the base of the PR and between 38b6d5d and cc51c08.

📒 Files selected for processing (2)
  • app/api/sandbox/upload/route.ts
  • lib/sandboxes/uploadSandboxFiles.ts
📝 Walkthrough

Walkthrough

The PR enhances sandbox file upload resilience by extending upload token configuration with addRandomSuffix: true and allowOverwrite: true, and refactoring the upload orchestration to collect partial successes via Promise.allSettled rather than failing entirely on the first error.

Changes

Cohort / File(s) Summary
Upload token configuration
app/api/sandbox/upload/route.ts
Extended onBeforeGenerateToken to include addRandomSuffix: true and allowOverwrite: true flags alongside existing maximumSizeInBytes limit, modifying filename and overwrite behavior during presigned uploads.
Upload result handling
lib/sandboxes/uploadSandboxFiles.ts
Replaced Promise.all with Promise.allSettled to collect both successes and failures, deriving blobFiles only from fulfilled uploads and throwing an error only if all uploads fail, allowing partial success scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • sweetmantech

Poem

🔄 When one file falls, the rest stand tall,
Random suffixes dance, overwrites enthrall,
allSettled now gathers the good with the pain—
Partial success flows through the upload lane! 📤

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning Multiple SOLID and clean code violations detected: DRY principle violated by duplicated magic number, SRP violated by oversized function, OCP violated by hardcoded configuration values, and dead code present. Extract magic numbers and configuration values to lib/consts.ts constants; refactor uploadSandboxFiles into focused functions with single responsibilities; remove or implement empty onUploadCompleted callback.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/REC-35-file-upload-blob-conflict

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 38b6d5dfa6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +50 to +54
const blobFiles = results
.filter(
(r): r is PromiseFulfilledResult<{ url: string; name: string }> =>
r.status === "fulfilled",
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Surface rejected blob uploads in partial-success path

When a multi-file upload has mixed outcomes, this code keeps only fulfilled results and drops rejected uploads without recording them, so the function can return success even though some selected files never made it to blob storage. In that scenario result.errors remains empty for callers (e.g. the drop hook’s success toast path), which misreports the operation as fully successful and can cause silent data loss from the user’s perspective.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/sandboxes/uploadSandboxFiles.ts (1)

39-65: ⚠️ Potential issue | 🟠 Major

Partial blob upload failures are swallowed instead of being returned to callers.

With Promise.allSettled, rejected uploads are filtered out, but their messages are never added to the returned errors. In mixed outcomes, this can hide failures from the UI even though some files failed at blob upload time.

Proposed fix
 export async function uploadSandboxFiles({
@@
 }): Promise<{ uploaded: UploadedFile[]; errors?: string[] }> {
   const results = await Promise.allSettled(
@@
   const blobFiles = results
@@
     .map((r) => r.value);
+
+  const blobUploadErrors = results
+    .filter((r): r is PromiseRejectedResult => r.status === "rejected")
+    .map((r) =>
+      r.reason instanceof Error
+        ? r.reason.message
+        : String(r.reason ?? "Failed to upload file to temporary storage"),
+    );
 
   if (blobFiles.length === 0) {
-    const firstError = results.find((r) => r.status === "rejected") as
-      | PromiseRejectedResult
-      | undefined;
     throw new Error(
-      firstError?.reason?.message ||
-        "Failed to upload files to temporary storage",
+      blobUploadErrors[0] || "Failed to upload files to temporary storage",
     );
   }
@@
-  return {
-    uploaded: data.uploaded || [],
-    errors: data.errors,
-  };
+  const allErrors = [...blobUploadErrors, ...(data.errors ?? [])];
+  return {
+    uploaded: data.uploaded || [],
+    ...(allErrors.length ? { errors: allErrors } : {}),
+  };
 }

As per coding guidelines, lib/**/*.ts utility functions must provide proper error handling.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/sandboxes/uploadSandboxFiles.ts` around lines 39 - 65, The current
Promise.allSettled handling drops rejected upload results so partial failures
are hidden; update the logic in uploadSandboxFiles (the block using
Promise.allSettled, results, blobFiles and upload) to collect rejected entries
from results, map them to structured error messages (including file.name and
rejection reason), and if any rejections exist return or throw an AggregateError
(or Error) that includes both the list of successfully uploaded blobFiles and a
detailed array/string of failed files and their error messages so callers can
surface partial-failure info to the UI.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@lib/sandboxes/uploadSandboxFiles.ts`:
- Around line 39-65: The current Promise.allSettled handling drops rejected
upload results so partial failures are hidden; update the logic in
uploadSandboxFiles (the block using Promise.allSettled, results, blobFiles and
upload) to collect rejected entries from results, map them to structured error
messages (including file.name and rejection reason), and if any rejections exist
return or throw an AggregateError (or Error) that includes both the list of
successfully uploaded blobFiles and a detailed array/string of failed files and
their error messages so callers can surface partial-failure info to the UI.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e7387b11-739e-47d0-8658-2984ad6bd153

📥 Commits

Reviewing files that changed from the base of the PR and between 0a6fc82 and 38b6d5d.

📒 Files selected for processing (2)
  • app/api/sandbox/upload/route.ts
  • lib/sandboxes/uploadSandboxFiles.ts

- Remove allowOverwrite: true (redundant with addRandomSuffix)
- Surface rejected blob uploads in the errors array so callers
  can report partial failures to the user

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sweetmantech sweetmantech merged commit 24e3ad4 into test Mar 30, 2026
3 checks passed
@sweetmantech sweetmantech deleted the fix/REC-35-file-upload-blob-conflict branch March 30, 2026 02:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants